package com.central.apps.controller;

import com.central.app.service.HandlerService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2022/8/5.
 */
@Slf4j
@RestController
@Api(tags = "测试controller")
@RequestMapping("/OverHaul")
public class PmListController {

    @Autowired
    private HandlerService handlerService;
    private final String WOTYPE = "5";//PM工单类型
    private final String STATUS = "1";//PM工单状态
    private final String DESCRIPTION = "PM生成工单";

    /*
    * 手动生成pm工单
    * */
    @PostMapping("/PmCreateWorkorder")
    public String PmCreateWorkorder(@RequestBody JSONObject PmInfo) throws Exception {
        log.info("===================wonum: " + PmInfo.get("insaenum") + "=========" + PmInfo.get("wonum"));

        JSONObject Pm = (JSONObject) PmInfo.get("PmInfo");
        if(Pm==null){
            Pm = PmInfo;
        }
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        try {
            //生成父工单,返回父工单编号
            String parentWorkNum = CreateWorkorder(Pm, null, null, null);
            String inspareacode = (String) Pm.get("linerepair");//检修路线
            if (inspareacode != null) {
                //查询检修路线下边是否有资产
                String sql = "select assetnum from gq_routes_asset where routesnum ='" + inspareacode+"'";
                List<Map<String, Object>> assetnumList = handlerService.findBySql(sql);
                if (assetnumList != null && assetnumList.size() > 0) {
                    for (Map<String, Object> objectMap : assetnumList) {
                        String assetnum = (String) objectMap.get("assetnum");
                        CreateWorkorder(Pm, parentWorkNum, assetnum, null);
                    }

                }
                //查询检修路线下边是否有位置
                String sql2 = "select location from gq_routes_location where routesnum =" + inspareacode;
                List<Map<String, Object>> locationList = handlerService.findBySql(sql2);
                if (locationList != null && locationList.size() > 0) {
                    for (Map<String, Object> objectMap : locationList) {
                        String location = (String) objectMap.get("location");
                        CreateWorkorder(Pm, parentWorkNum, location, null);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.put("code", "1");
            json.put("msg", "PM工单创建失败！");
            return json.toJSONString();
        }

        json.put("code", "0");
        json.put("msg", "PM工单创建成功！");


        return json.toJSONString();

    }
    /*
    * 选择作业计划之后，将作业计划中，子表数据插入到对应的工作任务，人员，物料表中
    * */
    @PostMapping("/InsertPmTask")
    @Transactional
    public String InsertPmTask(@RequestBody JSONObject insae) throws Exception {
        String wonum = (String) insae.get("wonum");
        String jpnum = (String) insae.get("workstandard");
        String insaenum = (String) insae.get("insaenum");
        List<Map<String, Object>> datas = new ArrayList<>();

        // 1.查询作业任务信息
        List<Map<String, Object>> list = handlerService.findBySql("select jobtask, abstract from gq_jobtask t where t.jpnum = '" + jpnum + "'");
        if (CollectionUtils.isNotEmpty(list)) {
            // 组织插入数据
            for (Map<String, Object> map : list) {
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("tasknum", map.get("jobtask"));// 任务编码
                insertMap.put("taskdesc", map.get("abstract"));// 任务描述
                insertMap.put("wonum", wonum);// 工单编码
                datas.add(insertMap);
            }

            // 插入作业任务信息
            handlerService.batchInsert("wptaskApp", "gq_task", datas);
        }

        // 2.查询作业计划-人员信息
        list = handlerService.findBySql("select labor, quantity, craft from gq_joblabor t where t.jpnum = '" + jpnum + "'");

        // 组织插入数据
        if (CollectionUtils.isNotEmpty(list)) {
            datas = new ArrayList<>();
            for (Map<String, Object> map : list) {
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("labor", map.get("labor"));// 员工ID
                insertMap.put("quantity", map.get("quantity"));// 数量
                insertMap.put("craft", map.get("craft"));// 工种
                insertMap.put("wonum", wonum);// 工单编码
                datas.add(insertMap);
            }

            // 插入作业人员信息
            handlerService.batchInsert("wplaborApp", "gq_wplabor", datas);
        }

        // 3.查询作业计划-物料信息
        list = handlerService.findBySql("select itemnum, itemqty, unitcost, linecost from gq_jobitem t where t.jpnum = '" + jpnum + "'");

        // 组织插入数据
        if (CollectionUtils.isNotEmpty(list)) {
            datas = new ArrayList<>();
            for (Map<String, Object> map : list) {
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("itemnum", map.get("itemnum"));// 物料编码
                insertMap.put("itemdesc", "");// 物料名称
                insertMap.put("itemqty", map.get("itemqty"));// 数量
                insertMap.put("unitcost", map.get("unitcost"));// 单位成本
                insertMap.put("linecost", map.get("linecost"));// 行成本
                insertMap.put("wonum", wonum);// 工单编码
                datas.add(insertMap);
            }

            // 插入作业人员信息
            handlerService.batchInsert("wpmaterialApp", "gq_wpmaterial", datas);
        }

        return null;
    }


    //插入到作业计划表中
    //wonum 工单编号，jpnum 作业计划编号
    public String PmWorkstandard(String wonum,String jpnum) throws Exception {
        //String wonum = (String) insae.get("wonum");
        //String jpnum = workstandard;
        //String insaenum = (String) insae.get("insaenum");
        List<Map<String, Object>> datas = new ArrayList<>();

        // 1.查询作业任务信息
        List<Map<String, Object>> list = handlerService.findBySql("select jobtask, abstract from gq_jobtask t where t.jpnum = '" + jpnum + "'");
        if (CollectionUtils.isNotEmpty(list)) {
            // 组织插入数据
            for (Map<String, Object> map : list) {
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("tasknum", map.get("jobtask"));// 任务编码
                insertMap.put("taskdesc", map.get("abstract"));// 任务描述
                insertMap.put("wonum", wonum);// 工单编码
                datas.add(insertMap);
            }

            // 插入计划作业任务信息
            handlerService.batchInsert("wptaskApp", "gq_wptask", datas);
            //插入实际工作子表
            handlerService.batchInsert("wptaskApp", "gq_acttask", datas);
        }

        // 2.查询作业计划-人员信息
        list = handlerService.findBySql("select labor, quantity, craft from gq_joblabor t where t.jpnum = '" + jpnum + "'");

        // 组织插入数据
        if (CollectionUtils.isNotEmpty(list)) {
            datas = new ArrayList<>();
            for (Map<String, Object> map : list) {
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("labor", map.get("labor"));// 员工ID
                insertMap.put("quantity", map.get("quantity"));// 数量
                insertMap.put("craft", map.get("craft"));// 工种
                insertMap.put("wonum", wonum);// 工单编码
                datas.add(insertMap);
            }

            // 插入作业人员信息
            handlerService.batchInsert("wplaborApp", "gq_wplabor", datas);
        }

        // 3.查询作业计划-物料信息
        list = handlerService.findBySql("select itemnum, itemqty, unitcost, linecost from gq_jobitem t where t.jpnum = '" + jpnum + "'");

        // 组织插入数据
        if (CollectionUtils.isNotEmpty(list)) {
            datas = new ArrayList<>();
            for (Map<String, Object> map : list) {
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("itemnum", map.get("itemnum"));// 物料编码
                insertMap.put("itemdesc", "");// 物料名称
                insertMap.put("itemqty", map.get("itemqty"));// 数量
                insertMap.put("unitcost", map.get("unitcost"));// 单位成本
                insertMap.put("linecost", map.get("linecost"));// 行成本
                insertMap.put("wonum", wonum);// 工单编码
                datas.add(insertMap);
            }

            // 插入作业人员信息
            handlerService.batchInsert("wpmaterialApp", "gq_wpmaterial", datas);
        }

        return null;
    }




    /*
    * parent为空，表示生成父工单，parent不为空表示生成子工单
    * */
    public String CreateWorkorder(@RequestBody JSONObject Pm, String parent, String assetnum, String location) throws Exception {

        //JSONObject Pm = (JSONObject) PmInfo.get("PmInfo");
        Map<String, Object> map = new HashMap<>();

        // 生成工单编码
        Map<String, Object> woMap = new HashMap<>();
        handlerService.addBizNum("workorderApp", "gq_workorder", woMap);

        //List<Map<String, Object>> woList = handlerService.findBySql("select wonum from gq_workorder order by createtime desc limit 1");
        // 查询工单编码
        //String wonum = (String) woList.get(0).get("wonum");//工单编号
        String wonum = (String) woMap.get("wonum");//工单编号
        //判断是否生成子工单还是父工单
        if (parent != null) {
            map.put("parent", parent);//父工单编号
            map.put("parentdesc", DESCRIPTION);//父工单描述

            String description = DESCRIPTION;
            if(assetnum!=null){
                description = DESCRIPTION+"_"+assetnum;
            }else {
                description = DESCRIPTION+"_"+location;
            }
            map.put("description", description);//工单描述
        } else {
            assetnum = (String) Pm.get("assetnum");//资产
            location = (String) Pm.get("location");//位置
            map.put("description", DESCRIPTION);//父工单描述
        }

        //String status = STATUS;//(String) Pm.get("status");//状态
        //String wotype =WOTYPE;//工单类型
        String classdesc = (String) Pm.get("classdesc");//班组
        String jpnum = (String) Pm.get("workstandard");//作业计划
        String jpdesc = (String) Pm.get("workstandarddesc");//作业计划描述
        String pmnum = (String) Pm.get("pmnum");//预防性维护编码
        String pmdesc = (String) Pm.get("description");//预防性维护描述
        Object leader =  Pm.get("person");//负责人
        // String acceptanceperson = (String) Pm.get("inspareacode");//验收负责人没有
        String inspareacode = (String) Pm.get("linerepair");//检修路线
        String inspareadesc = (String) Pm.get("linerepairdesc");//检修路线描述
        String startdate = (String) Pm.get("nextexecutetime");//计划开始时间


        if (jpnum != null) {
            map.put("jpnum", jpnum);//作业计划
            //作业计划不为空，将作业计划中的人员，物料，工作任务插入到对应的子表中
            try {
                PmWorkstandard(wonum,jpnum);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //String parent ="";
        map.put("wonum", wonum);//工单编号
        map.put("status", STATUS);//状态
        if (classdesc != null) {
            map.put("classdesc", classdesc);//班组
        }

        if (jpdesc != null) {
            map.put("jpdesc", jpdesc);//作业计划描述
        }
        if (pmnum != null) {
            map.put("pmnum", pmnum);//预防性维护编码
        }
        if (pmdesc != null) {
            map.put("pmdesc", pmdesc);//预防性维护描述
        }
        if (leader != null) {
            map.put("leader", leader);//责任人
        }
        if (inspareacode != null) {
            map.put("inspareacode", inspareacode);//检修路线
        }
        //map.put("acceptanceperson", acceptanceperson);//预防性维护编码
        if (inspareadesc != null) {
            map.put("inspareadesc", inspareadesc);//检修路线描述
        }
        if (startdate != null) {
            map.put("startdate", startdate);//计划开始时间
        }

        map.put("wotype", WOTYPE);

        if (assetnum != null) {
            map.put("assetnum", assetnum);//资产
        }
        if (location != null) {
            map.put("location", location);//位置
        }

        //总公司，分公司编号
        map.put("orgcode",  Pm.get("orgcode"));//总公司编号
        map.put("sitecode",  Pm.get("sitecode"));//分公司编号
        handlerService.insert("gq_workorder", map);
        //返回工单编号
        return wonum;
    }
}

